// pages/comments/comments.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    pxTorpx: 2, //px转化为rpx的系数
    leftLooks: 660,  //rpx
    topLooks: 790,  //rpx
    widthScreen: null,
    heightScreen: null,
    islongpress:0,
    navbarTitle: [
      "全部回复",
      "热度排名"
    ],
    commentTitle: '评论楼主',
    navbarActiveIndex: 0,
    isComment: false,
    topLooks: 600,
    content: '',
    type_id:2,
    topic_id: 0,
    collectBefore: true,
    mainLikeBefore: true
  },

  //获取评论内容
  onCommentContent: function(e){
    var content = e.detail.value;
    var that = this;
    that.setData({
      content: content
    })
  },

  //长按删除一级评论
  onDeleteFirstTopic: function(e){
    var that = this;
    var topic_id = e.currentTarget.dataset.topic_id;
    var user_id = e.currentTarget.dataset.user_id;
    var my_user_id = wx.getStorageSync('user_id');
    if(user_id != my_user_id){
      wx.showModal({
        title: '提示',
        content: '只能删除您自己发的评论~',
        showCancel: false
      })
    }else{
      wx.showModal({
        title: '提示',
        content: '确定删除这条评论？',
        success: res => {
          if(res.confirm){
            wx.request({
              url: app.globalData.targetUrl + 'discuss/topics/',
              //method: 'DELETE',
              data: {
                user_id: user_id,
                topic_id: topic_id,
                is_delete: 1
              },
              success: res => {
                that.onGetTopicMsg(that.data.topic_id);
              }
            })
          }
        }
      })
    }
  },
  //将编码后的八进制的emoji表情重新解码成十六进制的表情字符

  entitiesToUtf16: function (str) {

    return str.replace(/&#(\d+);/g, function (match, dec) {

      let H = Math.floor((dec - 0x10000) / 0x400) + 0xD800;

      let L = Math.floor(dec - 0x10000) % 0x400 + 0xDC00;

      return String.fromCharCode(H, L);

    });

  },
  //把utf16的emoji表情字符进行转码成八进制的字符

  utf16toEntities: function (str) {

    var patt = /[\ud800-\udbff][\udc00-\udfff]/g; // 检测utf16字符正则  

    return str.replace(patt, function (char) {

      var H, L, code;

      if (char.length === 2) {

        H = char.charCodeAt(0); // 取出高位  

        L = char.charCodeAt(1); // 取出低位  

        code = (H - 0xD800) * 0x400 + 0x10000 + L - 0xDC00; // 转换算法  

        return "&#" + code + ";";

      } else {

        return char;

      }

    });

  },
  //顶部导航条跳动
  onNavBarTap: function (event) {
    // 获取点击的navbar的index
    let navbarTapIndex = event.currentTarget.dataset.navbarIndex
    // 设置data属性中的navbarActiveIndex为当前点击的navbar
    this.setData({
      navbarActiveIndex: navbarTapIndex
    })
    var that = this;
    var topic_id = that.data.topic_id;
    if (navbarTapIndex == 0)  that.onGetTopicMsg(topic_id);
    else that.onGetOwnTopicMsg(topic_id);
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var topic_id = options.topic_id;
    var discuss_id = options.discuss_id;
    var that = this;
    var user_id = wx.getStorageSync('user_id');
    that.setData({
      topic_id: topic_id,
      discuss_id: discuss_id,
      my_user_id: user_id
    })
    that.onGetTopicMsg(topic_id);
    that.setData({
      view_cnt: parseInt(that.data.view_cnt) + 1
    })
    that.onAddVisit(topic_id);
    var that = this;
    //获取屏幕高
    wx.getSystemInfo({
      success: function (res) {
        //rpx
        var heightScreen = res.windowHeight * (750 / res.windowWidth);
        var topLooks = heightScreen - 100;
        that.setData({
          topLooks: topLooks
        });
      }
    })
    var pxTorpx = that.data.pxTorpx;
    //获取屏幕高宽
    wx.getSystemInfo({
      success: function (res) {
        //rpx
        that.setData({
          widthScreen: res.windowWidth * (750 / res.windowWidth),
          heightScreen: res.windowHeight * (750 / res.windowWidth),
          pxTorpx: (750 / res.windowWidth)
        });
      }
    });
  },

  //增加浏览+1
  onAddVisit: function(topic_id){
    var that = this;
    wx.request({
      url: app.globalData.targetUrl + 'discuss/topics/counter',
      data: {
        'topic_id': topic_id
      },
      success: res => {
        console.log(res.data);
      }
    })
  },

  onShow: function(){
    var that = this;
    var topic_id = that.data.topic_id;
    that.onGetTopicMsg(topic_id);
  },

  //一级评论热度排名
  onGetOwnTopicMsg:  function(topic_id){
    var that = this;
    wx.request({
      url: app.globalData.targetUrl + 'discuss/topics/' + topic_id,
      success: res => {
        var first = res.data.data.first_topics;
        var likeListBefore = that.data.likeListBefore;
        var like_list = that.data.like_list;
        var temp;
        for(var i = 1; i < first.length; i++){
          for(var j = i; j > 0 && first[j].like_cnt > first[j-1].like_cnt; j--){
            temp = first[j];
            first[j] = first[j-1];
            first[j-1] = temp;
            temp = likeListBefore[j];
            likeListBefore[j] = likeListBefore[j-1];
            likeListBefore[j-1] = temp;
            temp = like_list[j];
            like_list[j] = like_list[j-1];
            like_list[j-1] = temp;
          }
        }
        that.setData({
          first: first,
          likeListBefore: likeListBefore,
          like_list: like_list
        })
        that.onJudgeCollect();
      }
    })
  },

  //获取主贴所有信息
  onGetTopicMsg: function (topic_id) {
    var that = this;
    wx.request({
      url: app.globalData.targetUrl + 'discuss/topics/' + topic_id,
      success: res => {
        var main = res.data.data;       //主贴信息
        var first = main.first_topics;
        var like_list = [];             //一级评论点赞数
        var likeListBefore = [];        //一级评论点赞图标情况
        var imageList = [];             //一级评论图片列表
        for(var i = 0; i < first.length; i++){
          like_list[i] = first[i].like_cnt;
          if (first[i].image_urls != '') {
            imageList[i] = first[i].image_urls[0].slice(0, first[i].image_urls.length - 5) + "_tb.jpg";
          } else {
            imageList [i] = '';
          }
          likeListBefore[i] = true;    //一级评论，点赞列表图标的控制，true为不亮,初始化
        }
        var image_urls = '';
        if(main.image_urls != ''){
          image_urls = main.image_urls[0].slice(0, main.image_urls.length - 5) + "_tb.jpg";
        }
        main.description = that.entitiesToUtf16(main.description)
        for(var i=0;i<first.length;i++){
          first[i].content = that.entitiesToUtf16(first[i].content);
          for(var j = 0; j < first[i].second_topics.length; j++){
            first[i].second_topics[j].content = that.entitiesToUtf16(first[i].second_topics[j].content);
          }
        }
        that.setData({
          main: main,
          first: first,
          image_urls: image_urls,
          imageList: imageList,
          discuss_id: main.discuss_id,
          like_cnt: main.like_cnt,
          comment_cnt: first.length,
          like_list: like_list,
          view_cnt: main.view_cnt,
          likeListBefore: likeListBefore
        })
        that.onGetReplyName(first);     //拼接二级评论的名字
      }
    })
  },

  //拼接二级评论的名字
  onGetReplyName:function(first){
    var that = this;
    var user_id = wx.getStorageSync('user_id');
    var second = [];
    var secondName = [];
    for(var i = 0; i < first.length; i++){
      second[i] = first[i].second_topics;
      secondName[i] = [];
      for(var j = 0; j < second[i].length; j++){
        if(that.data.discuss_id == 1){
          if(user_id == second[i][j].user_id){
            secondName[i][j] = second[i][j].nick;
          }else{
            secondName[i][j] = (j + 1) + 'L';
          }
        }else{
          secondName[i][j] = second[i][j].nick;
        }
        for(var k = 0; k < second[i].length; k++){
          if (second[i][k].topic_id == second[i][j].to_topic_id && second[i][k].nick != secondName[i][j]){
            if (that.data.discuss_id == 1){
              if (second[i][k].user_id == user_id){
                secondName[i][j] = secondName[i][j] + ' 回复 ' + second[i][k].nick + ':';
              }else{
                secondName[i][j] = secondName[i][j] + ' 回复 ' + (k + 1) + 'L';
              }
              break;
            }else{
              secondName[i][j] = secondName[i][j] + ' 回复 ' + second[i][k].nick + ':';
              break;
            }
          }
        }
      }
    }
    that.setData({
      secondName: secondName
    })
    that.onJudgeCollect();
  },

  //判断是否已经收藏
  onJudgeCollect: function(){
    var that = this;
    var user_id = wx.getStorageSync('user_id');
    var topic_id = that.data.topic_id;
    wx.request({
      url: app.globalData.targetUrl + 'discuss/topics/collect/',
      method: 'GET',
      data:{
        user_id: user_id
      },
      success: res => {
        var collections = res.data.data;
        for(var i = 0; i < collections.length; i++){
          if(collections[i].topic_id == topic_id){
            that.setData({
              collectBefore: false
            })
            break;
          }
        }
        that.onJudgeCommentLike(topic_id, user_id);
      }
    })
  },

  //判断点赞情况
  onJudgeCommentLike: function(topic_id, user_id){
    var that = this;
    console.log("topic_id=" + topic_id + "user_id=" + user_id);
    wx.request({
      url: app.globalData.targetUrl + 'discuss/topics/like/',
      data:{
        topic_id: topic_id,
        user_id: user_id
      },
      success: res => {
        var likeList = res.data.data;
        var first = that.data.first;
        var likeListBefore = that.data.likeListBefore;
        console.log("一级评论帖子点赞列表topic_id:" + likeList);
        //判断主贴点赞情况
        var mainLikeBefore = that.data.mainLikeBefore;
        for(var i = 0; i < likeList.length; i++){
          if(topic_id == likeList[i]){
            that.setData({
              mainLikeBefore: false
            })
          }
        }
        //判断一级评论点赞情况
        for(var i = 0; i < first.length; i++){
          for(var j = 0; j < likeList.length; j++){
            if(first[i].topic_id == likeList[j]){
              likeListBefore[i] = false;
              break;
            }
          }
        }
        that.setData({
          likeListBefore: likeListBefore
        })
      }
    })
  },

  //点击图标，对该贴进行收藏或取消收藏
  onCollectTopic: function(){
    var that = this;
    var topic_id = that.data.topic_id;
    var user_id = wx.getStorageSync('user_id');
    var collectBefore = that.data.collectBefore;
    if(collectBefore){
      that.setData({
        collectBefore: false
      })
      wx.request({
        url: app.globalData.targetUrl + 'discuss/topics/collect/',
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        data: {
          user_id: user_id,
          topic_id: topic_id
        },
        success: res => {
          that.setData({
            collectBefore: false
          })
        }
      })
    }else{
      that.setData({
        collectBefore: true
      })
      wx.request({
        url: app.globalData.targetUrl + 'discuss/topics/collect/',
        //method: 'DELETE',
        method: 'GET',
        data: {
          user_id: user_id,
          topic_id: topic_id,
          is_delete: 1
        },
        success: res => {
          that.setData({
            collectBefore: true
          })
        }
      })
    }
  },

  //点赞
  onClickLike: function(e){
    var that = this;
    var click = e.currentTarget.dataset.like;
    var topic_id = that.data.topic_id;
    if(click == 'main'){
      //对主贴的点赞
      var mainLikeBefore = that.data.mainLikeBefore;
      if(mainLikeBefore){
        //未点赞  
        //post + count+1
        that.setData({
          like_cnt: parseInt(that.data.like_cnt)+1,
          mainLikeBefore: false
        })
        that.onTopicPost(topic_id);
      }else{
        //已点赞
        //delete + count-1
        that.setData({
          like_cnt: parseInt(that.data.like_cnt)-1,
          mainLikeBefore: true
        })
        that.onTopicDelete(topic_id);
      }
    }else{
      //对一级评论的点赞
      topic_id = click;
      var index = e.currentTarget.dataset.id;
      var like_list = that.data.like_list;
      var likeListBefore = that.data.likeListBefore;
      if(likeListBefore[index]){
        //点赞图片不亮的情况，+1
        likeListBefore[index] = false;
        like_list[index]++;
        that.setData({
          like_list: like_list,
          likeListBefore: likeListBefore
        })
        that.onTopicPost(topic_id);
      }else{
        //点赞图片亮起来的情况，-1
        likeListBefore[index] = true;
        like_list[index]--;
        that.setData({
          like_list: like_list,
          likeListBefore: likeListBefore
        })
        that.onTopicDelete(topic_id);
      }
    }
  },

  //topic帖子点赞的POST + COUNT+1
  onTopicPost: function(topic_id){
    var that = this;
    var user_id = wx.getStorageSync('user_id');
    wx.request({
      url: app.globalData.targetUrl + 'discuss/topics/like/',
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        'user_id': user_id,
        'topic_id': topic_id
      }
    })
  },

  //topic帖子点赞的DELETE + COUNT-1
  onTopicDelete: function(topic_id){
    var that = this;
    var user_id = wx.getStorageSync('user_id');
    wx.request({
      url: app.globalData.targetUrl + 'discuss/topics/like/',
      method: 'DELETE',
      data: {
        'user_id': user_id,
        'topic_id': topic_id
      }
    })
  },

  //点击取消评论栏
  cancelCommentArea: function(){
    var that = this;
    that.setData({
      isComment: !that.data.isComment
    })
  },

  //点击评论一级评论
  firstClickComment: function (e) {
    var that = this;
    that.setData({
      isComment: !that.data.isComment,
      father_topic_id: that.data.topic_id,
      type_id: '2',
      commentTitle: '评论楼主',
      to_topic_id: 0
    })
  },

  //点击评论二级评论
  secondClickComment: function(e){
    var that = this;
    var father_topic_id = e.currentTarget.dataset.father_topic_id;
    var to_topic_id = e.currentTarget.dataset.to_topic_id;
    var name = e.currentTarget.dataset.firstname;
    var table = e.currentTarget.dataset.table;
    if(table == "186" && that.data.discuss_id == 1){
      name = e.currentTarget.dataset.index + '楼';
    }
    that.setData({
      isComment: !that.data.isComment,
      father_topic_id: father_topic_id,
      type_id: '3',
      commentTitle: '回复 ' + name + ':',
      to_topic_id: to_topic_id  
    })
  },
 
  //发送评论信息 并收集formID
  onAddComment: function(e){
    var that = this;
    var content = that.data.content;
    if(!content){
      wx.showToast({
        title: '请填写评论内容！',
        duration: 2000,
        icon: 'none',
      })
    }else{
      that.setData({
        comment_cnt: parseInt(that.data.comment_cnt) + 1,
        content: '',
        isComment: false
      })
      var user_id = wx.getStorageSync('user_id');
      content = that.utf16toEntities(content);
      wx.request({
        url: app.globalData.targetUrl + 'discuss/topics/',
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        data: {
          'user_id': user_id,
          'father_topic_id': that.data.father_topic_id,
          'discuss_id': that.data.discuss_id,
          'type_id': that.data.type_id,
          'content': content,
          'to_topic_id': that.data.to_topic_id
        },
        success: res => {
          that.onGetTopicMsg(that.data.topic_id);
          wx.showToast({
            title: '评论成功！',
            duration: 2000
          })
        }
      })
    }
    // 收集formID
    var user_id = wx.getStorageSync('user_id');
    var formId = e.detail.formId;
    app.saveFormId(user_id, formId);
  },

  //发送增加评论图片
  onSendImageComment: function (e) {
    var that = this;
    qq.showLoading({
      title:'图片审核中'
    })
    wx.chooseImage({
      count: 1, //最多选择2张图片- that.data.banner.length,
      sizeType: ['compressed'],
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var img = res.tempFilePaths;
        //  console.log(res.tempFilePaths);
        if (res.tempFilePaths.count == 0) {
          return;
        }
        that.setData({
          img: img
        })
        //上传图片
        var user_id = wx.getStorageSync('user_id');
        wx.uploadFile({
          url: app.globalData.targetUrl + 'upload/image/',
          filePath: that.data.img[0],
          name: 'img',
          header: {
            'Content-type': 'application/x-www-form-urlencoded'
          },
          formData: {
            'user_id': user_id
          },
          success: function (res) {
            var data = JSON.parse(res.data).data;
            var image_id = data.image_id;
            var type_id = 2;
            wx.request({
              url: app.globalData.targetUrl + 'discuss/topics/',
              method: 'POST',
              header: {
                'content-type': 'application/x-www-form-urlencoded'
              },
              data: {
                'user_id': user_id,
                'father_topic_id': that.data.topic_id,
                'discuss_id': that.data.discuss_id,
                'title': '1',
                'description': '1',
                'content': '带图片的帖子',
                'type_id': type_id,
                'image_id': image_id,
                'to_topic_id': that.data.to_topic_id
              },
              success: res => {
                qq.hideLoading();
              }
            })
          },
        })
      }
    })
    qq.hideLoading();
  },

  //点击主贴图片放大 保存
  onBlowupImage: function (e) {
    var that = this;
    var list = [];
    var k = 0;
    for (var index in that.data.imageList) {
      if(that.data.imageList[index] != ''){
        list[k] = that.data.imageList[index];
        k++;
      }
    }
    var current = e.target.dataset.src;
    wx.previewImage({
      current: current, // 当前显示图片的http链接 
      urls: list // 需要预览的图片http链接列表 
    })
  },

  //点击主贴图片放大 保存
  previewImage: function (e) {
    var that = this;
    var list = [];
    for (var index in that.data.main.image_urls) {
        list[index] = that.data.main.image_urls[index]
    }
    var current = e.target.dataset.src;
    wx.previewImage({
      current: current, // 当前显示图片的http链接 
      urls: list // 需要预览的图片http链接列表 
    })
  },

  //小松鼠动画
  ClickFairy: function() {
    var that = this;
    var animation = wx.createAnimation({});
    var time = 440;
    var widthScreen = this.data.widthScreen;
    var heightScreen = this.data.heightScreen;
    var leftLooks = that.data.leftLooks;
    var topLooks = that.data.topLooks;
    var pxTorpx = that.data.pxTorpx;
    animation.translate(((widthScreen / 2 - leftLooks) - 20) / pxTorpx, ((heightScreen / 2 - topLooks) - 20) / pxTorpx).scale(0).opacity(0.4).step({ duration: time })
    this.setData({ queueData: animation.export() })
    this.sleep(time);
    wx.navigateTo({
      url: '/pages/launchTopic/launchTopic?discussId=' + that.data.discussId,
      success: res => {

      }
    })

  },
  imagetouchmove: function (e) {
    var that = this;
    var pxTorpx = that.data.pxTorpx;
    var left = e.touches[0].clientX * pxTorpx - 45;//rpx
    var top = e.touches[0].clientY * pxTorpx - 45;//rpx
    if (left < 0 && left) { left = 0 };
    if (left > that.data.widthScreen - 90) { left = that.data.widthScreen - 90 };
    if (top < 0) { top = 0 };
    if (top > that.data.heightScreen - 190) { top = that.data.heightScreen - 190 };

    that.setData({
      leftLooks: left,
      topLooks: top
    })
  },
  imagetouchend: function (e) {
    var that = this;
    var animation = wx.createAnimation({});
    var widthScreen = this.data.widthScreen;
    var left_before = that.data.leftLooks;
    if (left_before == that.data.widthScreen - 90) return;
    var left = that.data.widthScreen - 90;
    that.setData({
      leftLooks: left
    })
    var time = 300;
    var n1 = left_before / widthScreen; //形变系数
    if (n1 < 0.2) { n1 = 0.2 }
    var n2 = (widthScreen - left_before) / widthScreen * 0.7;
    var pxTorpx = that.data.pxTorpx;
    console.log(pxTorpx);
    console.log("n1:", 1 - n1, (90 / pxTorpx) * (1 - n1));
    animation.scale(n1, 1 + n2).translate((90 / pxTorpx) * (1 - n1), 0).step({ duration: time });
    that.setData({ queueData: animation.export() });
    that.sleep(time);
    animation.scale(1, 1).translate(0, 0).step({ duration: time });
    that.setData({ queueData: animation.export() });

  },

  //延时函数
  sleep: function (numberMillis) {
    var now = new Date();
    var exitTime = now.getTime() + numberMillis;
    while (true) {
      now = new Date();
      if (now.getTime() > exitTime)
        return;
    }
  },
  onReachBottom: function () {
    var that = this;
    var page_cnt = that.data.page_cnt + 10;
    this.setData({
      page_cnt: page_cnt
    })
    that.onGetTopicMsg(that.data.topic_id);
  },
})